import 'package:flutter/material.dart';
import 'package:craze/common/widgets/login_dialog.dart';
import 'package:craze/services/service_locator.dart';
import 'package:craze/stores/auth_store.dart';
import 'package:craze/common/utils/my_toast.dart';

/// 认证辅助工具类
/// 用于处理登录状态检查和认证相关操作
class AuthHelper {
  /// 私有构造函数，防止实例化
  AuthHelper._();

  /// 获取AuthStore实例
  static final AuthStore _authStore = getIt<AuthStore>();

  /// 验证用户是否已登录
  static bool isAuthenticated() {
    return _authStore.isLoggedIn;
  }

  /// 检查登录状态并执行相应操作
  ///
  /// [context] - 当前上下文
  /// [onAuthenticated] - 已登录时执行的回调
  /// [onUnauthenticated] - 未登录时执行的回调
  static void checkLoginState({
    required BuildContext context,
    required Function() onAuthenticated,
    required Function() onUnauthenticated,
  }) {
    if (isAuthenticated()) {
      onAuthenticated();
    } else {
      onUnauthenticated();
    }
  }

  /// 执行需要登录的安全操作
  ///
  /// [context] - 当前上下文
  /// [onAuthNeeded] - 需要登录时的回调函数，返回是否继续显示登录对话框
  /// [onAuthorized] - 已登录时的操作回调
  /// [returnPath] - 登录成功后的返回路径
  static Future<void> executeSecureOperation({
    required BuildContext context,
    Future<bool> Function()? onAuthNeeded,
    required Future<void> Function() onAuthorized,
    String? returnPath,
  }) async {
    // 已登录，直接执行操作
    if (isAuthenticated()) {
      await onAuthorized();
      return;
    }

    // 未登录，先执行onAuthNeeded回调，如果返回true，则显示登录对话框
    if (onAuthNeeded != null) {
      final shouldShowAuthDialog = await onAuthNeeded();
      if (!shouldShowAuthDialog) {
        return;
      }
    }

    // 显示登录对话框
    await LoginDialog.show(context, returnPath: returnPath);
  }

  /// 用户登录认证
  ///
  /// [context] - 当前上下文
  /// [username] - 用户名
  /// [password] - 密码
  /// [onSuccess] - 登录成功的回调
  static Future<void> authenticate({
    required BuildContext context,
    required String username,
    required String password,
    required VoidCallback onSuccess,
  }) async {
    if (username.isEmpty || password.isEmpty) {
      MyToast.showError(context, 'Please enter username and password');
      return;
    }

    // 显示加载提示
    final loadingToast = MyToast.showLoading(context, 'Authenticating...');

    try {
      // 添加短暂延迟以确保UI更新
      await Future.delayed(const Duration(milliseconds: 100));

      // 执行登录
      final success = await _authStore.login(username, password);

      // 模拟网络请求延迟，确保加载效果显示约1秒
      await Future.delayed(const Duration(milliseconds: 1000));

      // 关闭加载提示
      MyToast.dismiss(loadingToast);

      if (success) {
        MyToast.showSuccess(context, 'Authentication successful');
        // 添加短暂延迟，让用户看到成功提示后再跳转
        await Future.delayed(const Duration(milliseconds: 800));
        onSuccess();
      } else {
        MyToast.showError(
          context,
          _authStore.errorMessage ?? 'Authentication failed, please try again',
        );
      }
    } catch (e) {
      // 确保加载提示显示了至少1秒
      await Future.delayed(const Duration(milliseconds: 1000));
      // 关闭加载提示
      MyToast.dismiss(loadingToast);

      MyToast.showError(
        context,
        'Error during authentication: ${e.toString()}',
      );
    }
  }

  /// 注册新用户
  ///
  /// [context] - 当前上下文
  /// [username] - 用户名
  /// [password] - 密码
  /// [confirmPassword] - 确认密码
  /// [onSuccess] - 注册成功的回调
  static Future<void> registerNewAccount({
    required BuildContext context,
    required String username,
    required String password,
    required String confirmPassword,
    required VoidCallback onSuccess,
  }) async {
    // 表单验证
    if (username.isEmpty || password.isEmpty || confirmPassword.isEmpty) {
      MyToast.showError(context, 'Please complete all fields');
      return;
    }

    if (password != confirmPassword) {
      MyToast.showError(context, 'Passwords do not match');
      return;
    }

    // 显示加载提示
    final loadingToast = MyToast.showLoading(context, 'Creating account...');

    try {
      // 添加短暂延迟以确保UI更新
      await Future.delayed(const Duration(milliseconds: 100));

      // 执行注册
      final success = await _authStore.register(
        username: username,
        password: password,
        name: username,
        email: '',
      );

      // 模拟网络请求延迟，确保加载效果显示约1秒
      await Future.delayed(const Duration(milliseconds: 1000));

      // 关闭加载提示
      MyToast.dismiss(loadingToast);

      if (success) {
        MyToast.showSuccess(context, 'Account created successfully');
        // 添加短暂延迟，让用户看到成功提示后再跳转
        await Future.delayed(const Duration(milliseconds: 800));
        onSuccess();
      } else {
        MyToast.showError(
          context,
          _authStore.errorMessage ?? 'Registration failed, please try again',
        );
      }
    } catch (e) {
      // 确保加载提示显示了至少1秒
      await Future.delayed(const Duration(milliseconds: 1000));
      // 关闭加载提示
      MyToast.dismiss(loadingToast);

      MyToast.showError(context, 'Error during registration: ${e.toString()}');
    }
  }

  /// 用户退出登录
  ///
  /// [context] - 当前上下文
  /// [onSuccess] - 退出登录成功的回调
  static void signOut({
    required BuildContext context,
    required VoidCallback onSuccess,
  }) {
    _authStore.logout();
    MyToast.showSuccess(context, 'Signed out successfully');
    onSuccess();
  }
}
